package org.linlinjava.litemall.admin.service.order_manage;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.beanutils.BeanUtils;
import org.linlinjava.litemall.admin.vo.locks.Address;
import org.linlinjava.litemall.admin.vo.service_order.*;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.order_manage.AgedmallServiceOrderManageMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.vo.order_manage.ServiceOrderPramVo;
import org.linlinjava.litemall.db.vo.service_order.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author wj
 * @date 2021/8/13 10:20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AgedmallServiceOrderAdminService {


    @Resource
    private AgedmallServiceOrderManageMapper agedmallServiceOrderManageMapper;

    @Resource
    private AgedmallServiceOrderMapper agedmallServiceOrderMapper;

    @Resource
    private AgedmallOnlineServiceMapper agedmallOnlineServiceMapper;

    @Resource
    private AgedmallDepartmentMapper agedmallDepartmentMapper;

    @Resource
    private AgedmallDoctorInfoMapper agedmallDoctorInfoMapper;

    @Resource
    private LitemallOrderMapper litemallOrderMapper;

    @Resource
    private LitemallUserMapper litemallUserMapper;

    public Integer serviceOrderStatChange(String stat){
        switch (stat){
            case "notAppointment":
                return 1;
            case "notService":
                return 2;
            case "finished":
                return 3;
            case "overtime":
                return 4;
            case "closed":
                return 5;
            case "notPay":
            default:
                return 0;
        }
    }


    public Object onlineOrderList(OnlineOrderListVo onlineOrderListVo){
        SelectServiceOrderListDto selectServiceOrderListDto=new SelectServiceOrderListDto();
        if(ObjectUtil.isNull(onlineOrderListVo.getAddress())){
            onlineOrderListVo.setAddress(new Address());
        }
        if(ObjectUtil.isNull(onlineOrderListVo.getTime())){
            onlineOrderListVo.setTime(new TimeSlot());
        }
        selectServiceOrderListDto.setPhone(onlineOrderListVo.getPhone());
        selectServiceOrderListDto.setStartTime(onlineOrderListVo.getTime().getStartTime());
        selectServiceOrderListDto.setEndTime(onlineOrderListVo.getTime().getEndTime());
        selectServiceOrderListDto.setProvinceId(onlineOrderListVo.getAddress().getShengId());
        selectServiceOrderListDto.setCityId(onlineOrderListVo.getAddress().getShiId());
        selectServiceOrderListDto.setStat(serviceOrderStatChange(onlineOrderListVo.getState()));
        Page page=PageHelper.startPage(onlineOrderListVo.getPage(), onlineOrderListVo.getLimit());
        List<ServiceOrderBackDto> serviceOrderList = agedmallServiceOrderManageMapper.getServiceOrderList(selectServiceOrderListDto);
        Map<String,Object> map=new HashMap<>();
        map.put("total",page.getTotal());
        map.put("data",serviceOrderList);
        return ResponseUtil.ok(map);
    }

    /**
     * 获取在线订单列表
     * @return
     */
    public Object onlineOrderList(ServiceOrderPramVo serviceOrderPramVo){
        Map<String,Object> map=new HashMap<>();
        try {
            Page page=PageHelper.startPage(serviceOrderPramVo.getPage(), serviceOrderPramVo.getLimit());
            if(serviceOrderPramVo.getPast()!= null){
                serviceOrderPramVo.setLatelyTime(this.getPastDate(serviceOrderPramVo.getPast()));
            }
            //查询服务订单信息
            List<ServiceOrderDto> serviceOrderDtoList = agedmallServiceOrderManageMapper.getOnlineOrderList(serviceOrderPramVo);
            List<ServiceOrderDto> serviceOrderDtoLists = new ArrayList<>(serviceOrderDtoList.size());
            for(ServiceOrderDto sod : serviceOrderDtoList){
                ServiceOrderDto serviceOrderDto = new ServiceOrderDto();
                AgedmallDoctorInfo agedmallDoctorInfo = this.getAgedmallDoctorInfo(sod.getDoctorId());
                if(agedmallDoctorInfo != null){
                    sod.setDoctorName(agedmallDoctorInfo.getDoctorName());
                }
                BeanUtils.copyProperties(serviceOrderDto,sod);
                serviceOrderDtoLists.add(serviceOrderDto);
            }
            map.put("total",page.getTotal());
            map.put("data",serviceOrderDtoLists);
        }catch (Exception e){
           e.printStackTrace();
        }
        return ResponseUtil.ok(map);
    }

    private AgedmallDoctorInfo getAgedmallDoctorInfo(Long id){
        AgedmallDoctorInfoExample example = new AgedmallDoctorInfoExample();
        example.or().andUserIdEqualTo(id);
        AgedmallDoctorInfo adi = agedmallDoctorInfoMapper.selectOneByExample(example);
        return adi;
    }

    private String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    /**
     * 根据不同的服务订单状态加载订单详情页
     * @param serviceOrderId
     * @return
     */
    public Object serviceIdOrderDetailInfo(Long serviceOrderId){
        AgedmallServiceOrder agedmallServiceOrder = agedmallServiceOrderMapper.selectByPrimaryKey(serviceOrderId);
        if(agedmallServiceOrder == null){
            return ResponseUtil.ok();
        }
        ServiceOrderDetailsDto serviceOrderDetailsDto = new ServiceOrderDetailsDto();
        serviceOrderDetailsDto.setStat(agedmallServiceOrder.getStat());

        //服务订单信息
        ServiceOrderInfo serviceOrderInfo = this.getServiceOrderInfo(agedmallServiceOrder);
        serviceOrderDetailsDto.setServiceOrderInfo(serviceOrderInfo);

        //买家信息
        BuyingLeadsInfo buyingLeadsInfo = this.getBuyingLeadsInfo(agedmallServiceOrder);
        serviceOrderDetailsDto.setBuyingLeadsInfo(buyingLeadsInfo);

        //服务详情
        ServiceMessage serviceMessage = this.getServiceMessage(agedmallServiceOrder);
        serviceOrderDetailsDto.setServiceMessage(serviceMessage);

        return ResponseUtil.ok(serviceOrderDetailsDto);
    }

    /**
     * 服务详情
     * @param agedmallServiceOrder
     * @return
     */
    private ServiceMessage getServiceMessage(AgedmallServiceOrder agedmallServiceOrder){
        ServiceMessage serviceMessage = new ServiceMessage();
        serviceMessage.setWeixinPhone(agedmallServiceOrder.getWechatphone());
        //根据服务id查询服务信息
        AgedmallOnlineService agedmallOnlineService =
                agedmallOnlineServiceMapper.selectByPrimaryKey(agedmallServiceOrder.getServiceId());
         if(agedmallOnlineService != null){
             serviceMessage.setServiceName(agedmallOnlineService.getName());
             //优惠preferential
             serviceMessage.setPreferential(agedmallOnlineService.getOriginalPrice().subtract(agedmallServiceOrder.getServicePrice()).doubleValue());
         }

         //服务医生信息
        DoctorInformation doctorInformation = this.getDoctorInformation(agedmallServiceOrder);
         if(doctorInformation != null){
             serviceMessage.setDoctorInformation(doctorInformation);
         }

        //预约信息
        ServiceSubscribe serviceSubscribe = this.getServiceSubscribe(agedmallServiceOrder);
         if(serviceSubscribe != null){
             serviceMessage.setServiceSubscribe(serviceSubscribe);
         }


        //咨询信息
        ServiceUserDescribe serviceUserDescribe = this.getServiceUserDescribe(agedmallServiceOrder);
         if(serviceUserDescribe != null){
             serviceMessage.setServiceUserDescribe(serviceUserDescribe);
         }

        return serviceMessage;
    }


    /**
     * 咨询信息
     * @param agedmallServiceOrder
     * @return
     */
    private ServiceUserDescribe getServiceUserDescribe(AgedmallServiceOrder agedmallServiceOrder){
        ServiceUserDescribe serviceUserDescribe = null;
        if(agedmallServiceOrder != null){
            serviceUserDescribe = new ServiceUserDescribe();
            serviceUserDescribe.setUserDescribe(agedmallServiceOrder.getUserDescribe());
            if(agedmallServiceOrder.getDescribeImgs() != null || serviceUserDescribe.getUserDescribe() != null){
                String serviceImg[] = agedmallServiceOrder.getDescribeImgs().split(",");
                List<String> stringList = null;
                if(serviceImg.length > 0 ){
                    stringList = new ArrayList<>();
                    for(String s : serviceImg){
                        stringList.add(s);
                    }
                }
                serviceUserDescribe.setDescribeImgs(stringList);
            }else{
                serviceUserDescribe.setDescribeImgs(new ArrayList<>());
            }
        }
        if(serviceUserDescribe.getUserDescribe() !=null || serviceUserDescribe.getDescribeImgs() != null){
            return serviceUserDescribe;
        }
        return null;
    }

    /**
     * 预约信息
     * @param agedmallServiceOrder
     * @return
     */
    private ServiceSubscribe getServiceSubscribe(AgedmallServiceOrder agedmallServiceOrder){
        ServiceSubscribe serviceSubscribe = null;
        if(agedmallServiceOrder != null){
             DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if(agedmallServiceOrder.getFullAppointTime()!= null){
                serviceSubscribe = new ServiceSubscribe();
                String addTime = df.format(agedmallServiceOrder.getFullAppointTime());
                serviceSubscribe.setTime(addTime);
            }
        }

        return serviceSubscribe;
    }

    /**
     * 服务医生
     * @param agedmallServiceOrder
     * @return
     */
    private DoctorInformation getDoctorInformation(AgedmallServiceOrder agedmallServiceOrder){
        AgedmallDepartment agedmallDepartment = null;
        DoctorInformation doctorInformation = null;
        if(agedmallServiceOrder.getDepid() != null){
            doctorInformation = new DoctorInformation();
            //根据科室id查询科室信息
            agedmallDepartment = agedmallDepartmentMapper.selectByPrimaryKey(agedmallServiceOrder.getDepid().intValue());
            if(agedmallDepartment != null){
                doctorInformation.setDepartmentName(agedmallDepartment.getName());
                doctorInformation.setDepartmentId(agedmallDepartment.getId());
            }
            //根据医生id查询医生信息
            AgedmallDoctorInfoExample doctorInfoExample = new AgedmallDoctorInfoExample();
            doctorInfoExample.or().andUserIdEqualTo(agedmallServiceOrder.getDoctorId());
            AgedmallDoctorInfo agedmallDoctorInfo = agedmallDoctorInfoMapper.selectOneByExample(doctorInfoExample);
            if(agedmallDoctorInfo != null){
                doctorInformation.setDoctorName(agedmallDoctorInfo.getDoctorName());
            }
        }
        return doctorInformation;
    }

    /**
     * 服务订单信息
     * @param agedmallServiceOrder
     * @return
     */
    private ServiceOrderInfo getServiceOrderInfo(AgedmallServiceOrder agedmallServiceOrder){
        ServiceOrderInfo soi = new ServiceOrderInfo();
        soi.setOrderSn(agedmallServiceOrder.getOrderSn());
        soi.setSubId(agedmallServiceOrder.getSubid());
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String addTime = df.format(agedmallServiceOrder.getAddTime());
        soi.setCreated(addTime);
        return soi;
    }

    /**
     * 买家信息
     * @param agedmallServiceOrder
     * @return
     */
    private BuyingLeadsInfo getBuyingLeadsInfo(AgedmallServiceOrder agedmallServiceOrder){
        BuyingLeadsInfo buyingLeadsInfo = new BuyingLeadsInfo();
        buyingLeadsInfo.setUserPhone(agedmallServiceOrder.getWechatphone());
        buyingLeadsInfo.setOrderPrice(agedmallServiceOrder.getServicePrice().doubleValue());
        buyingLeadsInfo.setNote(agedmallServiceOrder.getHelptext());
        buyingLeadsInfo.setPayType("微信支付");
        //查询用户姓名
       // String userName = agedmallServiceOrderManageMapper.getUserNameInfo(agedmallServiceOrder.getOrderId().toString());

        //根据大订单号查询用户id
        if(agedmallServiceOrder.getOrderId() == null){
            return buyingLeadsInfo;
        }
        LitemallOrder litemallOrder = litemallOrderMapper.selectByPrimaryKey(agedmallServiceOrder.getOrderId().intValue());
        if(litemallOrder != null){
            LitemallUser litemallUser = litemallUserMapper.selectByPrimaryKey(litemallOrder.getUserId());
            if(litemallUser != null){
                buyingLeadsInfo.setUserName(litemallUser.getNickname());
            }
        }
        return buyingLeadsInfo;
    }




    public Object serviceOrderDetail(ServiceOrderDetailVo serviceOrderDetailVo){
        List<ServiceOrderDetailBackDto> serviceOrderDetailList = agedmallServiceOrderManageMapper.getServiceOrderDetailList(serviceOrderDetailVo.getOrderId());
        return ResponseUtil.ok(serviceOrderDetailList);
    }

    /**
     * 在线服务订单变更为已关闭状态
     * @param id
     * @return
     */
    public Object cancleServiceOrder(String id){
        if(id == null || "".equals(id)){
            return ResponseUtil.fail("服务订单id不能为空");
        }
       try {
           AgedmallServiceOrder agedmallServiceOrder = agedmallServiceOrderMapper.selectByPrimaryKey(Long.parseLong(id));
           if(ObjectUtil.isNull(agedmallServiceOrder)){
               return ResponseUtil.fail(615,"服务订单id不存在");
           }
           agedmallServiceOrder.setStat(7);//设置为取消状态
           agedmallServiceOrderMapper.updateByPrimaryKey(agedmallServiceOrder);
       }catch (Exception e){
           return ResponseUtil.fail("关闭订单系统出现异常");
       }
        return ResponseUtil.ok();
    }


    public Object distributeDoctor(DistributeDoctorVo distributeDoctorVo){
        AgedmallServiceOrder agedmallServiceOrder =
                agedmallServiceOrderMapper.selectByPrimaryKeySelective(distributeDoctorVo.getServiceOderId().longValue());
        if(ObjectUtil.isNull(agedmallServiceOrder)){
            return ResponseUtil.fail(615,"服务订单id不存在");
        }
        if(agedmallServiceOrder.getStat() == 2 || agedmallServiceOrder.getStat() == 3){
            //根据医生id查询用户登录id
            AgedmallDoctorInfo agedmallDoctorInfo = agedmallDoctorInfoMapper.selectByPrimaryKey(distributeDoctorVo.getDoctorId().longValue());
            agedmallServiceOrder.setDoctorId(agedmallDoctorInfo.getUserId());
            agedmallServiceOrder.setAllot(1);//表示后台分配医生
            agedmallServiceOrderMapper.updateByPrimaryKey(agedmallServiceOrder);
            return ResponseUtil.ok();
        }
        return ResponseUtil.ok("该订单目前状态，无法分配医生");
    }


    /**
     *  点击完成按钮完成订单
     */
    public Object finishOrder(FinishOrderVo finishOrderVo){
        if(finishOrderVo.getOrderId() == null || "".equals(finishOrderVo.getOrderId()) || finishOrderVo.getOrderId() == 0){
            return ResponseUtil.fail("服务订单id不能为空!");
        }
        AgedmallServiceOrder agedmallServiceOrder = agedmallServiceOrderMapper.selectByPrimaryKey(finishOrderVo.getOrderId());
        if(ObjectUtil.isNull(agedmallServiceOrder)){
            return ResponseUtil.fail(615,"服务订单id不存在");
        }
        agedmallServiceOrder.setStat(5);
        agedmallServiceOrderMapper.updateByPrimaryKeySelective(agedmallServiceOrder);
        return ResponseUtil.ok();

    }


}
